<template>
  <div class="container">
    <Breadcrumb :items="['menu.list', '厂家']" />
    <a-card class="general-card" title="厂家">
      <formCom
        ref="formComDom"
        :option="searchOption"
        :key-count="state.keyCount"
        @serachFn="serachFn"
      />
      <div class="right-btn">
        <el-button plan type="primary" @click="actionFn('add', {})"
          >新增厂家</el-button
        >
      </div>
      <kxTable
        :table-data="list"
        :column-list="columnList"
        border
        :loading="listLoading"
      >
        <template #options="{ row }">
          <el-button link type="primary" @click="actionFn('edit', row)"
            >编辑</el-button
          >
          <el-button link plan type="danger" @click="actionFn('del', row)"
            >删除</el-button
          >
        </template>
      </kxTable>
      <Pagination
        v-model:limit="pageSize"
        v-model:page="currentPage"
        :total="total"
        @pagination="getList()"
        @pagination-size-change="getList(1)"
      />
      <!-- 新增厂家弹框 -->
      <el-dialog
        v-model="showAddModal"
        :title="titleType[dialogType]"
        width="600px"
      >
        <el-form :model="newItem" label-width="100px">
          <formCom
            ref="formComDom"
            :option="option"
            :key-count="state.keyCount"
            @submit-fn="submitFn"
            @cancle-fn="closeDialog"
          />
        </el-form>
        <!-- <template #footer>
          <span class="dialog-footer">
            <el-button @click="onCancel">取 消</el-button>
            <el-button type="primary" @click="onConfirm">确 定</el-button>
          </span>
        </template> -->
      </el-dialog>
    </a-card>
  </div>
</template>

<script setup lang="ts">
  import { ref, onMounted, reactive } from 'vue';
  import type { FormInstance, FormRules } from 'element-plus';
  import { useRouter, useRoute } from 'vue-router';
  import { ElMessageBox, ElMessage } from 'element-plus';
  import { useList } from '@/use/index';
  import {
    manufacturerListApi,
    manufacturerAddApi,
    manufacturerUpdateApi,
    manufacturerDelApi,
  } from '@/utils/apiConfig';
  import { setManufacturer } from '@/utils/util';
  const router = useRouter();
  const route = useRoute();
  const {} = route.query;
  const state = reactive({ keyCount: 1 });

  const {
    searchForm,
    list,
    listLoading,
    total,
    currentPage,
    pageSize,
    getList,
    handleSearch,
    resetSearch,
  } = useList(manufacturerListApi);
  if (!searchForm.value) {
    searchForm.value = {
      manufacturerName: '', // 与后端搜索参数一致
    } as any;
  }

  const titleType: any = {
    add: '新增厂家',
    edit: '编辑厂家',
  };
  const option = reactive({
    labelWidth: '100px',
    isBetween: false, // false = float 布局
    showSubmit: true,
    position: 'left',
    // submitName: '新增资产',
    formList: [
      {
        label: '生产厂家',
        val: '',
        field: 'manufacturerName',
        type: 'input',
        width: '100%',
        rightMargin: true,
        maxLength: 50,
        require: true,
      },
      {
        label: '备注',
        val: '',
        field: 'remark',
        type: 'input',
        width: '100%',
        maxLength: 100,
        rightMargin: true,
      },
    ],
  });
  const searchOption = reactive({
    labelWidth: '80px',
    isBetween: false, // false = float 布局
    position: 'left',
    formList: [
      {
        label: '名称',
        val: '',
        field: 'manufacturerName',
        type: 'input',
        width: '340px',
        rightMargin: true,
      },
    ],
    showSreach: true, // 是否显示搜索按钮
  });
  const showAddModal = ref(false);
  const columnList = reactive([
    {
      label: '生产厂家',
      prop: 'manufacturerName',
      minWidth: '120px',
    },
    {
      label: '备注',
      prop: 'remark',
      minWidth: '120px',
    },

    {
      slot: 'operation',
      width: '130',
      label: '操作',
      prop: 'options',
      notooltip: true,
      fixed: 'right',
    },
  ]);
  function inits() {
    getList();
    setManufacturer();
  }
  function serachFn(obj: any) {
    console.log('serachFn', obj);
    searchForm.value = {
      ...obj,
    };
    inits();
  }
  function closeDialog() {
    showAddModal.value = false;
    option.formList.forEach((item) => {
      item.val = '';
    });
    state.keyCount += 1;
  }
  function submitFn(obj: any) {
    console.log(111111, obj);
    // list.value.push(obj);
    if (dialogType.value === 'add') {
      manufacturerAddApi(obj)
        .then((res) => {
          console.log('add-res', res);
          inits();
          ElMessage({
            message: '新增厂家成功',
            type: 'success',
          });
        })
        .catch((err) => {
          console.log('add-err', err);
        });
    } else {
      const id = dialogItem.value?.id;
      manufacturerUpdateApi({ ...obj, id })
        .then((res) => {
          console.log('update-res', res);
          inits();
          ElMessage({
            message: '更新厂家成功',
            type: 'success',
          });
        })
        .catch((err) => {
          console.log('update-err', err);
        });
    }
    closeDialog();
  }

  function searchFn(obj: any) {
    console.log('searchFn', obj);
  }
  // 弹框与表单

  const addFormRef = ref<FormInstance>();
  const newItem = ref({
    departmentName: '',
    departmentType: '',
    desc: '',
    tag: '',
  });
  const dialogType = ref('add');
  const dialogItem = ref({});
  function actionFn(type: 'add' | 'del' | 'edit', item: any) {
    console.log(type, item);
    dialogType.value = type;
    dialogItem.value = item;
    switch (type) {
      case 'add':
        showAddModal.value = true;
        break;
      case 'del':
        console.log(item.departmentName);
        ElMessageBox.confirm('确定删除吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        })
          .then(() => {
            console.log('del-api');
            const manufacturerNo = item?.manufacturerNo;
            manufacturerDelApi({ addPath: manufacturerNo })
              .then((res) => {
                console.log('del-res', res);
                inits();
                ElMessage({
                  message: '删除厂家成功',
                  type: 'success',
                });
              })
              .catch((err) => {
                console.log('del-err', err);
              });
          })
          .catch(() => {});
        break;

      case 'edit':
        console.log('edit', item);
        option.formList.forEach((one) => {
          one.val = item[one.field];
        });
        state.keyCount += 1;
        showAddModal.value = true;
        break;

      default:
        break;
    }
  }
  onMounted(() => {
    inits();
  });
</script>

<style lang="less" scoped>
  .container {
    padding: 20px;
  }
</style>
